import io, json
from .utils import post
from .wrapper import subthread, withWaitSound
import ui
URL = 'http://op.juhe.cn/onebox/exchange/query?key=a89325357c166174b42fe068c1dcfd1a'
def getExchangeRateInfo():
    res = post(URL)
    if not res:
        raise Exception(_('No result.'))
    data = json.loads(res)
    if data['error_code'] != 0:
        raise Exception(data['reason'])
    result = data['result']
    if not result:
        raise Exception(_('No result.'))
    buff = io.StringIO()
    buff.write('<table title="汇率表">') # 表格开始
    buff.write('<tr>') # 表头开始
    [buff.write(f'<th>{i}</th>') for i in ('货币名称', '交易单位', '现汇买入价', '现钞买入价', '现钞卖出价', '中行折算价')]
    buff.write('</tr>') # 表头结束
    for item in result['list']:
        buff.write('<tr>') # 一行数据
        [buff.write(f'<td>{i}</td>') for i in item]
        buff.write('</tr>') # 表头结束
    buff.write('</table>') # 表格结束
    buff.write('更新时间： %s' % result['update'])
    res = buff.getvalue()
    buff.close()
    return res
@withWaitSound
@subthread
def viewExchangeRate():
    try:
        res = getExchangeRateInfo()
        ui.browseableMessage(res, '汇率详情', True)
    except Exception as e:
        ui.message(_(f'{e}'))